<template>
  <div class="login-container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form
          hide-required-asterisk
          :model="state"
          ref="ruleFormRef"
          :rules="rules"
          class="login_form"
        >
          <h1>{{ setting.title }}</h1>
          <el-form-item label="username" prop="username">
            <el-input
              v-model="state.username"
              placeholder="请输入用户名"
              :prefix-icon="User"
            ></el-input>
          </el-form-item>
          <el-form-item label="Password" prop="password">
            <el-input
              ref="passwordRef"
              v-model="state.password"
              :type="passwordType"
              :prefix-icon="Lock"
            ></el-input>
            <span class="show-pwd" @click="showPwd">
              <SvgIcon
                :width="16"
                :height="16"
                :name="passwordType === 'password' ? 'eye' : 'open'"
              />
            </span>
          </el-form-item>
          <el-form-item>
            <el-button
              size="large"
              class="login_btn"
              :loading="loading"
              type="primary"
              @click="login"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import setting from '@/setting'
export default defineComponent({
  name: 'Login'
})
</script>
<script lang="ts" setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref, reactive, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import useUserStore from '@/stores/user/user'
import { ElNotification, type FormInstance, type FormRules } from 'element-plus'
// 账号密码
const state = reactive<{ username: string; password: string }>({
  username: 'admin',
  password: '111111'
})

const ruleFormRef = ref<FormInstance>()
// 密码输入框
const passwordRef = ref<HTMLInputElement>()
const passwordType = ref('password')

// 登录按钮加载状态
const loading = ref(false)
// 路由器对象
const router = useRouter()
const route = useRoute()

//登录方法
const login = async () => {
  await ruleFormRef.value?.validate() //验证表单会返回一个Promise对象
  loading.value = true
  try {
    const res = await useUserStore().login(state)
    if (res?.code === 20000) {
      loading.value = false
      ElNotification({ title: getTime(), message: '欢迎回来', type: 'success' })
      router.push({
        path: (route.query.redirect as string) || '/'
      })
    }
  } catch (error) {
    loading.value = false
    ElNotification({ message: (error as Error).message, type: 'error' })
  }
}

// 获取当天时间几点
const getTime = () => {
  let time: string | number = new Date().getHours()
  return time < 9
    ? '早上好'
    : time < 12
      ? '上午好'
      : time < 14
        ? '中午好'
        : time < 18
          ? '下午好'
          : '晚上好'
}

/*
切换密码的显示/隐藏
*/
const showPwd = () => {
  if (passwordType.value === 'password') {
    passwordType.value = 'text'
  } else {
    passwordType.value = 'password'
  }
  nextTick(() => {
    passwordRef.value?.focus()
  })
}

const validatePassword = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback('密码不能为空！')
  } else if (value.length < 6) {
    callback(new Error('密码长度不能小于6位'))
  } else {
    callback()
  }
}

const validateUsername = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback('用户名不能为空！')
  } else if (value.length < 4) {
    callback(new Error('用户名长度不能小于4位'))
  } else {
    callback()
  }
}
const rules = reactive<FormRules<typeof state>>({
  username: [{ required: true, validator: validateUsername, trigger: 'blur' }], //用户名规则
  password: [{ required: true, validator: validatePassword, trigger: 'blur' }] //密码规则
})
</script>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
  color: white;
}
.login-container {
  width: 100%;
  height: 100vh;
  background: (url('/src/assets/background-34eb3d2b.jpg') no-repeat left center);

  .login_form {
    h1 {
      color: white;
      font-size: 35px;
      padding-bottom: 40px;
      text-align: center;
    }
    padding: 20px;
    position: absolute;
    width: 30%;
    top: 35vh;
    margin-right: 20px;
    background-color: rgba($color: #4556c8, $alpha: 0.3);
    border-radius: 2%;
    .show-pwd {
      position: absolute;
      right: 10px;
      top: 5px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }
    .login_btn {
      width: 100%;
    }
  }
}
</style>
